// 好友管理和实时通讯功能
document.addEventListener('DOMContentLoaded', () => {
    const friendsList = document.getElementById('friends-list');
    const friendRequests = document.getElementById('friend-requests');
    const messagesList = document.getElementById('messages-list');
  
    // 加载好友列表
    const loadFriends = async () => {
      try {
        const token = localStorage.getItem('token');
        const response = await fetch('/friends/list', {
          headers: {
            'Authorization': `Bearer ${token}`,
          },
        });
        const friends = await response.json();
        if (response.ok) {
          friendsList.innerHTML = '';
          friends.forEach(friend => {
            const friendElement = document.createElement('div');
            friendElement.className = 'friend';
            friendElement.innerHTML = `
              <h3>${friend.profile.name}</h3>
              <button class="message-btn" data-id="${friend._id}">Message</button>
              <button class="unfriend-btn" data-id="${friend._id}">Unfriend</button>
            `;
            friendsList.appendChild(friendElement);
          });
  
          // 添加消息事件监听
          document.querySelectorAll('.message-btn').forEach(btn => {
            btn.addEventListener('click', () => {
              const friendId = btn.getAttribute('data-id');
              const messageText = prompt('Enter your message:');
              if (messageText) {
                sendMessage(friendId, messageText);
              }
            });
          });
  
          // 添加取消好友事件监听
          document.querySelectorAll('.unfriend-btn').forEach(btn => {
            btn.addEventListener('click', async () => {
              const friendId = btn.getAttribute('data-id');
              try {
                const token = localStorage.getItem('token');
                const response = await fetch(`/friends/${friendId}`, {
                  method: 'DELETE',
                  headers: {
                    'Authorization': `Bearer ${token}`,
                  },
                });
                if (response.ok) {
                  loadFriends();
                }
              } catch (error) {
                console.error('Failed to unfriend:', error);
              }
            });
          });
        }
      } catch (error) {
        console.error('Failed to load friends:', error);
      }
    };
  
    // 加载好友请求
    const loadFriendRequests = async () => {
      try {
        const token = localStorage.getItem('token');
        const response = await fetch('/friends/requests', {
          headers: {
            'Authorization': `Bearer ${token}`,
          },
        });
        const requests = await response.json();
        if (response.ok) {
          friendRequests.innerHTML = '';
          requests.forEach(request => {
            if (request.status === 'pending') {
              const requestElement = document.createElement('div');
              requestElement.className = 'friend-request';
              requestElement.innerHTML = `
                <p>${request.from.profile.name} wants to be friends</p>
                <button class="accept-btn" data-id="${request._id}">Accept</button>
                <button class="reject-btn" data-id="${request._id}">Reject</button>
              `;
              friendRequests.appendChild(requestElement);
            }
          });
  
          // 添加接受好友请求事件监听
          document.querySelectorAll('.accept-btn').forEach(btn => {
            btn.addEventListener('click', async () => {
              const requestId = btn.getAttribute('data-id');
              try {
                const token = localStorage.getItem('token');
                const response = await fetch(`/friends/accept/${requestId}`, {
                  method: 'POST',
                  headers: {
                    'Authorization': `Bearer ${token}`,
                  },
                });
                if (response.ok) {
                  loadFriendRequests();
                  loadFriends();
                }
              } catch (error) {
                console.error('Failed to accept friend request:', error);
              }
            });
          });
  
          // 添加拒绝好友请求事件监听
          document.querySelectorAll('.reject-btn').forEach(btn => {
            btn.addEventListener('click', async () => {
              const requestId = btn.getAttribute('data-id');
              try {
                const token = localStorage.getItem('token');
                const response = await fetch(`/friends/reject/${requestId}`, {
                  method: 'POST',
                  headers: {
                    'Authorization': `Bearer ${token}`,
                  },
                });
                if (response.ok) {
                  loadFriendRequests();
                }
              } catch (error) {
                console.error('Failed to reject friend request:', error);
              }
            });
          });
        }
      } catch (error) {
        console.error('Failed to load friend requests:', error);
      }
    };
  
    // 发送好友请求
    const sendFriendRequest = async (userId) => {
      try {
        const token = localStorage.getItem('token');
        const response = await fetch('/friends/request', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ to: userId }),
        });
        if (response.ok) {
          alert('Friend request sent successfully!');
        }
      } catch (error) {
        console.error('Failed to send friend request:', error);
        alert('Failed to send friend request. Please try again.');
      }
    };
  
    // 发送消息
    const sendMessage = (receiverId, messageText) => {
      const socket = io('http://localhost:5000');
      socket.emit('message', {
        from: localStorage.getItem('user'),
        to: receiverId,
        text: messageText,
        timestamp: new Date().toISOString(),
      });
      socket.on('message', (message) => {
        console.log('Received message:', message);
        loadMessages();
      });
    };
  
    // 加载消息
    const loadMessages = async () => {
      try {
        const token = localStorage.getItem('token');
        const response = await fetch('/messages', {
          headers: {
            'Authorization': `Bearer ${token}`,
          },
        });
        const messages = await response.json();
        if (response.ok) {
          messagesList.innerHTML = '';
          messages.forEach(message => {
            const messageElement = document.createElement('div');
            messageElement.className = 'message';
            messageElement.innerHTML = `
              <p><strong>${message.from.profile.name}:</strong> ${message.text}</p>
              <small>${new Date(message.timestamp).toLocaleString()}</small>
            `;
            messagesList.appendChild(messageElement);
          });
        }
      } catch (error) {
        console.error('Failed to load messages:', error);
      }
    };
  
    // 初始化
    loadFriends();
    loadFriendRequests();
    loadMessages();
  });